package com.atguigu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/5
 */
@RestController
@RequestMapping("/consumer")
@RefreshScope
@Slf4j
public class OrderNacosController {

    @Value("${service-url.nacos-user-service}")
    private String serverUrl;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id){
        return restTemplate.getForObject(serverUrl+"/payment/nacos/"+id,String.class);
    }

    @GetMapping("/sentinel/blockHandler/{id}")
    @SentinelResource(value = "testD",blockHandler = "deal_testDBlock",fallback = "deal_testDError",exceptionsToIgnore = {IllegalArgumentException.class})
    public String testD(@PathVariable long id)
    {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(id%3==0){
            return "testD";
        } else if(id%3==1){
            throw new NullPointerException();
        } else throw new IllegalArgumentException();
    }

    @GetMapping("/sentinel/blockHandler4thread/{id}")
    @SentinelResource(value = "testE",blockHandler = "deal_testDBlock",fallback = "deal_testDError",exceptionsToIgnore = {IllegalArgumentException.class})
    public String testE(@PathVariable long id)
    {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            return "testE";
        }
    }

    public String deal_testDBlock(long idn, BlockException be){
        log.debug(idn+"异常，异常内容："+be);
        return "deal_testDBlock"+idn+"异常，异常内容："+be;
    }

    public String deal_testDError(@PathVariable long id,Throwable e){
        log.debug(id+"异常，异常内容："+e);
        return "deal_testDError"+id+"异常，异常内容："+e;
    }
}
